package com.it.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.util.SaResult;
import com.github.pagehelper.PageInfo;
import com.it.annotation.ClearCache;
import com.it.annotation.SystemLog;
import com.it.bean.User;
import com.it.dto.UserDTO;
import com.it.dto.UserRoleDTO;
import com.it.page.PageImpl;
import com.it.page.PageQuery;
import com.it.service.UserService;
import com.it.vo.UserVo;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {

    private final UserService userService;

    @SaCheckRole("admin")
    @PostMapping("/page")
    @Cacheable(cacheNames = "users", key = "T(java.util.Objects).hash(#pageQuery.page, #pageQuery.pageSize, #pageQuery.queryBody)")
    public SaResult page(@RequestBody PageQuery<UserDTO> pageQuery) {
        PageInfo<UserVo> pageInfo = userService.page(pageQuery);
        return SaResult.data(PageImpl.of(pageInfo));
    }

    @PostMapping("/list")
    @Cacheable(cacheNames = "users", key = "T(java.util.Objects).hash(#root.methodName)")
    public SaResult list(@RequestBody User user) {
        List<User> users = userService.list(user);
        return SaResult.data(users);
    }

    @ClearCache
    @PostMapping("/delete/{id}")
    @SystemLog(value = "用户数据", method = "数据删除")
    @CacheEvict(value = "users", allEntries = true)
    @SaCheckPermission(value = {"user-delete",}, orRole = {"admin"})
    public SaResult del(@PathVariable("id") Long id) {
        userService.delete(id);
        return SaResult.ok();
    }

    @ClearCache
    @PostMapping("/save")
    @SystemLog(value = "用户数据", method = "新增修改")
    @CacheEvict(value = "users", allEntries = true)
    @SaCheckPermission(value = {"user-add", "user-edit",}, orRole = {"admin"})
    public SaResult save(@RequestBody UserRoleDTO userRole) {
        userService.save(userRole);
        return SaResult.ok();
    }

}